package com.gmics.unifiq;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import com.caldroid.CaldroidFragment;
import com.caldroid.CaldroidListener;
import com.gmics.android.R;
import com.gmics.unifiq.controller.EntityController;
import com.gmics.unifiq.controller.GooglePlace;
import com.gmics.unifiq.entity.Event;
import com.gmics.unifiq.entity.Place;
import com.gmics.unifiq.entity.PlaceDetails;
import com.gmics.unifiq.entity.PlaceList;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class UpdateEvent extends FragmentActivity {
	private EntityController controller = new EntityController();
	private TextView groupTV, creatorTV;
	private EditText titleET, dateET, timeET, descET;
	private AutoCompleteTextView locationACTV;
	private Button updateBtn;
	private ProgressDialog pDialog = null;
	private Event event;
	private CaldroidFragment dialogCaldroidFragment;
	private Bundle state;
	private static int MAX_DAYS = 30;
	private int currentHour = 0, currentMinute = 0;
	private Date selectedDate = null;
	private GooglePlace googlePlace = new GooglePlace();
	private PlaceList locationList;
	private PlaceDetails locationDetails;
	private String[] locationACArr, locationTypeArr;
	private ArrayList<PlaceDetails> locationArr = new ArrayList<PlaceDetails>();
	public static String KEY_REFERENCE = "reference"; // id of the place
	public static String KEY_NAME = "name"; // name of the place
	private ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
	private String locationRef = null;
	private int result = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.update_event_layout);
		
		state = savedInstanceState;
		locationTypeArr = getResources().getStringArray(R.array.location_type);
		new LoadUpdateEvent().execute();
    
	}
	
    class LoadUpdateEvent extends AsyncTask<String, String, String> {
   	 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdateEvent.this);
            pDialog.setMessage("Loading update event page...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 

        protected String doInBackground(String... args) {
			try {
				locationList = googlePlace.radarSearch(locationTypeArr);
				for (Place p : locationList.results) {
					locationArr.add(googlePlace.getPlaceDetails(p.reference));
				}
						
				locationACArr = new String[locationArr.size()];
				for (int i = 0; i < locationArr.size(); i++){
					locationACArr[i] = locationArr.get(i).result.name;
					HashMap<String, String> map = new HashMap<String, String>();
	
					map.put(KEY_REFERENCE, locationArr.get(i).result.reference);
					map.put(KEY_NAME, locationArr.get(i).result.name);
	
					placesListItems.add(map);					
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return null;
        }
 
        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {

                	Bundle b = getIntent().getExtras();
                	event = (Event) b.getSerializable("eventToUpdate");
                	locationDetails = (PlaceDetails) b.getSerializable("locationDetails");
                	
            		groupTV = (TextView) findViewById(R.id.group_tv);
            		creatorTV = (TextView) findViewById(R.id.creator_tv);
            		titleET = (EditText) findViewById(R.id.title_et);
            		locationACTV = (AutoCompleteTextView) findViewById(R.id.location_actv);
            		dateET = (EditText) findViewById(R.id.date_et);
            		timeET = (EditText) findViewById(R.id.time_et);
            		descET = (EditText) findViewById(R.id.desc_et);
            		updateBtn = (Button) findViewById(R.id.update_btn);
            		
            		groupTV.setText(b.getString("groupName"));
            		creatorTV.setText(b.getString("creatorName"));
            		titleET.setHint(event.getName());
            		locationACTV.setText(locationDetails.result.name);
            		dateET.setHint(EntityController.convertDateTimeToString(event.getDateTime()));
            		timeET.setHint(EntityController.timeToString(event.getDateTime()));
            		descET.setHint(event.getDescription());
            		
            		final CaldroidListener caldroidListener = new CaldroidListener() {

            			@Override
            			public void onChangeMonth(int month, int year) {
            			}

            			@Override
            			public void onSelectDate(Date date, View view) {				
            				Date currentDate = EntityController.dateTimeToDate(Calendar.getInstance().getTime());
            				long diffDays = (date.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000);
            				
            				if (EntityController.dateTimeToDate(date).compareTo(currentDate) < 0){
            					Toast.makeText(UpdateEvent.this, "Selected date has passed. Please choose a valid date.",
            							Toast.LENGTH_LONG).show();
            				}
            				else if (diffDays > MAX_DAYS){
            					Toast.makeText(UpdateEvent.this, "Date is set too far into the future. Please set within a month.",
            							Toast.LENGTH_LONG).show();
            				}
            				else{
            					selectedDate = date;
            					dateET.setText(EntityController.convertDateTimeToString(date));
            					dialogCaldroidFragment.dismiss();
            				}
            			}
            		};
            		
            		dateET.setOnClickListener(new OnClickListener() {

            			@Override
            			public void onClick(View v) {
            				// TODO Auto-generated method stub
            				dialogCaldroidFragment = new CaldroidFragment();
            				dialogCaldroidFragment.setCaldroidListener(caldroidListener);

            				// If activity is recovered from rotation
            				final String dialogTag = "CALDROID_DIALOG_FRAGMENT";
            				if (state != null) {
            					dialogCaldroidFragment.restoreDialogStatesFromKey(
            							getSupportFragmentManager(), state,
            							"DIALOG_CALDROID_SAVED_STATE", dialogTag);
            					Bundle args = dialogCaldroidFragment.getArguments();
            					if (args == null) {
            						args = new Bundle();
            						dialogCaldroidFragment.setArguments(args);
            					}
            					args.putString(CaldroidFragment.DIALOG_TITLE,
            							"Select a date");
            				} else {
            					// Setup arguments
            					Bundle bundle = new Bundle();
            					// Setup dialogTitle
            					bundle.putString(CaldroidFragment.DIALOG_TITLE,
            							"Select a date");
            					dialogCaldroidFragment.setArguments(bundle);
            				}

            				dialogCaldroidFragment.show(getSupportFragmentManager(),
            						dialogTag);
            			}

            		});

            		timeET.setOnClickListener(new OnClickListener() {

            			@Override
            			public void onClick(View v) {
            				// TODO Auto-generated method stub
            				Calendar c = Calendar.getInstance();
            				currentHour = c.get(Calendar.HOUR_OF_DAY);
            				currentMinute = c.get(Calendar.MINUTE);

            				TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
            					@Override
            					public void onTimeSet(TimePicker view, int selectedHour,
            							int selectedMinute) {
            						
            						String time = new String();
            						if (selectedHour < 10){
            							time = "0" + String.valueOf(selectedHour) + ":";
            						}
            						else{
            							time = String.valueOf(selectedHour) + ":";
            						}
            						
            						if (selectedMinute < 10){
            							time += "0" + String.valueOf(selectedMinute);
            						}
            						else{
            							time += String.valueOf(selectedMinute);
            						}
            						
            						timeET.setText(time);
            					}
            				};

            				TimePickerDialog tpd = new TimePickerDialog(UpdateEvent.this,
            						timePickerListener, currentHour, currentMinute, false);
            				tpd.show();

            			}

            		});
            		
					SimpleAdapter locationAdapter = new SimpleAdapter(UpdateEvent.this,
							placesListItems, R.layout.location_list_item,
							new String[] { KEY_REFERENCE, KEY_NAME }, new int[] {
									R.id.location_ref, R.id.location_tv });
					
            		
            		//ArrayAdapter<CharSequence> locationAdapter = new ArrayAdapter<CharSequence>(UpdateEvent.this, android.R.layout.select_dialog_item, new String[] {"a", "b", "c"});
					locationACTV.setThreshold(1);
            		locationACTV.setAdapter(locationAdapter);
            		
            		locationACTV.setOnItemClickListener(new OnItemClickListener(){
						@Override
						public void onItemClick(AdapterView<?> adapterView, View v,
								int pos, long id) {
							// TODO Auto-generated method stub
							int selectedPos = 0;
							HashMap<String, String> map = (HashMap<String, String>) adapterView.getItemAtPosition(pos);
							for (int i = 0; i < placesListItems.size(); i++){
								if (map.get(KEY_REFERENCE).equals(locationArr.get(i).result.reference)){
									selectedPos = i;
									break;
								}
							}
							
    						locationACTV.setText(locationArr.get(selectedPos).result.name);
            				locationRef = locationArr.get(selectedPos).result.reference;

						}
            			
            		});
            		
            		updateBtn.setOnClickListener(new OnClickListener(){

            			@Override
            			public void onClick(View arg0) {
            				// TODO Auto-generated method stub
            				
            				String name = titleET.getText().toString();
            				String time = timeET.getText().toString();
            				String desc = descET.getText().toString();          				
            				Date tempDate = selectedDate;
            				String tempTime = time;
            				
            				if (selectedDate == null && !time.equals("")){
            					tempDate = EntityController.dateTimeToDate(event.getDateTime());
            				}
            				
            				if (selectedDate != null && time.equals("")){
            					tempTime = String.valueOf(EntityController.dateTimeToTime(event.getDateTime()));
            				}
            				
            				if ( (name != null && !name.equals("")) || selectedDate != null || time != null || locationRef != null || (desc != null && !desc.equals("")) ){
            					boolean eventSuccess = controller.updateEvent(event.getId(), name, tempDate, tempTime, locationRef, desc);
            					
            					ArrayList<String> originalArr = new ArrayList<String>(), updatedArr = new ArrayList<String>();
            					
            					if (locationRef != null){
            						originalArr.add(locationACTV.getHint().toString());
            						updatedArr.add(locationACTV.getText().toString());
            					}
            					
            					if (selectedDate != null){
            						originalArr.add(dateET.getHint().toString());
            						updatedArr.add(dateET.getText().toString());
            					}
            					
            					if (time != null){
            						originalArr.add(timeET.getHint().toString());
            						updatedArr.add(timeET.getText().toString());
            					}
            					
            					boolean notificationSuccess = controller.createNotification(0, event.getId(), originalArr, updatedArr);
            					boolean userNotificationSuccess = false;
            					
            					if (notificationSuccess){
            						int notificationID = controller.retrieveLatestNotification().getId();
            						ArrayList<Integer> userIDArr = controller.retrieveGroupUserID(event.getGroupID());
            						userNotificationSuccess = controller.createUserNotification(notificationID, userIDArr);
            					}
            					
            					if (eventSuccess && notificationSuccess && userNotificationSuccess) {
            						Toast.makeText(UpdateEvent.this,
            								"Event successfully updated!",
            								Toast.LENGTH_LONG).show();
            							result = RESULT_OK;
            						onBackPressed();
            					} else {
            						Toast.makeText(
            								UpdateEvent.this,
            								"Event not successfully updated. Please try again.",
            								Toast.LENGTH_LONG).show();
            					}
            				}
            					

            			}
            			
            		});
                }
            });
            
        }
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public void onBackPressed() {
		Bundle b = new Bundle();
		Intent viewEventScreen = new Intent(this, ViewEvent.class);
		if (result == RESULT_OK){
			b.putSerializable("updatedEvent", controller.retrieveEventByID(event.getId()));
			viewEventScreen.putExtras(b);
		}

		setResult(result, viewEventScreen);
		super.onBackPressed();
	}

}
